﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UnityScriptEngine;

namespace EnrollmentSystem
{
    public partial class frmUserManager : Form
    {
        UnityProcessor proc = new UnityProcessor();
        Threader t = new Threader();
        Tesselation ts = new Tesselation("lowgate", 128);
        UnityScript[] dat = new UnityScript[0];

        //Operation Attributes
        bool AddNew = false;
        int curEdit = -1;
        UnityElement curUser;

        public frmUserManager()
        {
            InitializeComponent();
            InitializeFrameSliderForm();
        }
        private void InitializeForm()
        {
            //GUI Events
          
            btnAdd.Click += new EventHandler(delegate
            {
                AddNew = true;
                btnDelete.Enabled = false;
                DetailControl(true);
            });
            btnCancel.Click += new EventHandler(delegate
            {
                AddNew = false;
                DetailControl(false);
                foreach (Control ctl in grpDetails.Controls)
                {
                    if (ctl is TextBox) ((TextBox)ctl).Text = "";
                }
            });
            btnSave.Click += new EventHandler(delegate
            {
                if (txtPWD.Text == txtCPWD.Text)
                {
                    SaveUser();
                    grpDetails.Enabled = false;
                }
                else
                {
                    MessageBox.Show("Password mistmatch!", "Save User", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            });
            btnDelete.Click += new EventHandler(delegate
            {
                if (MessageBox.Show("Do you wish to continue?",
                    "Delete User",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No) return;
                DeleteUser();
                grpDetails.Enabled = false;
            });
            txtLvl.TextChanged += new EventHandler(delegate
            {
                int lvl = 0;
                txtLvl.ForeColor = Color.Black;
                if (!int.TryParse(txtLvl.Text, out lvl))
                {
                    txtLvl.ForeColor = Color.Red;
                }
                else
                {
                    if (lvl < 1 || lvl > 5)
                    {
                        txtLvl.ForeColor = Color.Red;
                    }
                }
            });
            grdItems.DoubleClick += new EventHandler(delegate
            {
                curEdit = grdItems.SelectedRows[0].Index;

                dat[1].Data_Get(curEdit, out curUser);

                txtID.Text = curUser.Data_GetField(0).ToString();
                txtUID.Text = curUser.Data_GetField(1).ToString();
                txtPWD.Text = ts.Tesselate(curUser.Data_GetField(2).ToString());
                txtLvl.Text = curUser.Data_GetField(3).ToString();
                txtCPWD.Text = txtPWD.Text;

                btnDelete.Enabled = true;
                DetailControl(true);
                AddNew = false;
            });
            //UnityScriptEngine Events
            proc.ProcessCompleted += new ProcessHandler(proc_ProcessCompleted);
            proc.ProcessError += new ProcessHandler(proc_ProcessError);

            DetailControl(true);
            grpDetails.Enabled = false;
            t.MethodCall(LoadUsers);
        }
        //UnityScriptEngine
        void proc_ProcessError(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                MessageBox.Show(desc);
                switch (id)
                {
                    case "LOADUSERS":
                        DetailControl(true);
                        grpDetails.Enabled = false;
                        break;
                    case "DELETEUSER":
                    case "SAVEUSER":
                        DetailControl(true);
                        break;
                }
            });
        }
        void proc_ProcessCompleted(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                switch (id)
                {
                    case "DELETEUSER":
                    case "SAVEUSER":
                    case "LOADUSERS":
                        proc.DBPUX_Data_Fetch(out dat);
                        grdItems.DataSource = dat[0].ToDataTable();
                        AddNew = false;
                        DetailControl(false);
                        foreach (Control ctl in grpDetails.Controls)
                        {
                            if (ctl is TextBox) ((TextBox)ctl).Text = "";
                        }
                        FormatGrid();
                        break;
                }
            });
        }
        //Data Operations
        void LoadUsers()
        {
            UnityScript u = new UnityScript("LOADUSERS", 5);
            u.Script_Add(Script.DBPUX_BEGIN);
            u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fUID AS 'ID Number', fName AS 'Name', fStamp FROM tblusers");
            u.Script_Add(Script.DBPUX_QUERY, "SELECT * FROM tblusers");
            u.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(u);
        }
        void SaveUser()
        {
            UnityScript u = new UnityScript("SAVEUSER", 5);
            //u.Script_Add(Script.DBPUX_OPEN);
            u.Script_Add(Script.DBPUX_BEGIN);
            if (AddNew)
            {
                u.Script_Add(Script.DBPUX_INSERT, "tblusers(fUID, fName, fLevel, fPWD)",
                    new string[]{
                        txtID.Text,
                        txtUID.Text,
                        txtLvl.Text,
                        ts.Tesselate(txtPWD.Text)
                    });
            }
            else
            {
                u.Script_Add(Script.DBPUX_UPDATE, string.Format("tblusers SET " +
                    "fUID='{0}', fName='{1}', fLevel='{2}', fPWD='{3}'", txtID.Text, txtUID.Text, txtLvl.Text, ts.Tesselate(txtPWD.Text)),
                    string.Format("(fID='{0}') AND (fStamp='{1}')", curUser.Data_ID.ToString(), curUser.Data_Stamp));
            }
            u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fUID AS 'ID Number', fName AS 'Name', fStamp FROM tblusers");
            u.Script_Add(Script.DBPUX_QUERY, "SELECT * FROM tblusers");
            u.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(u);
        }
        void DeleteUser()
        {
            UnityScript u = new UnityScript("DELETEUSER", 5);
            u.Script_Add(Script.DBPUX_BEGIN);

            u.Script_Add(Script.DBPUX_DELETE, "tblusers",
                string.Format("(fID='{0}') AND (fStamp='{1}')", curUser.Data_ID.ToString(), curUser.Data_Stamp));

            u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fUID AS 'ID Number', fName AS 'Name', fStamp FROM tblusers");
            u.Script_Add(Script.DBPUX_QUERY, "SELECT * FROM tblusers");
            u.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(u);
        }
        //GUI Operations
        void DetailControl(bool s)
        {
            grdItems.Enabled = !s;
            grpDetails.Visible = s;
            grpDetails.Enabled = s;
            btnAdd.Enabled = !s;
        }
        void FormatGrid()
        {
            foreach (DataGridViewColumn col in grdItems.Columns)
            {
                col.Width = (grdItems.Width / grdItems.Columns.Count) - 10;
            }
        }
    }
}
